/**
 * Created by yl on 2016/5/5 0005.
 */
/*function removeAt(array,idx)
{
    if(! Array.prototype.isPrototypeOf(array)){
        return null;
    }
    var idx = parseInt(idx),
        iLen = idx.length;
    if(idx < 0 || idx >= iLen){
        return null;
    }
    var aRet = [];//与NULL不同
    return aRet=array.slice(0,idx).concat(array.slice(idx+1));
}*/
// Application Service Used by the Vue Layer(View Layer)
var AppService = {
    urlroot: "http://euvee.vicp.co/rest/site/",
    init: function(){
        Vue.http.options.root = this.urlroot;
    },
    find: function(inputQuery, pagenum, pagesteps, items, success_callback, error_callback){
        var url = this.urlroot;
        Vue.http.get(url, function(data, status, request){
            var i = data.length;
            success_callback(data, status, request);
        })
            .error(function (data, status, request) {
                alert("svc.find: fetch data from backend server failed! " + data + ' ' + status + ' ' + request);
                if (error_callback != null)
                {
                    error_callback(data, status, request);
                }
            });
    },

/*    generate: function(inputQuery, pagenum, pagesteps, callback){
        var items = [];
        for (var i=0; i<pagesteps; i++)
        {
            items.push(this.newItem(i, (i % 2 == 0)));
        }
        if (typeof callabck == "function")
            callback(items);
    },*/

    /* get an item with its detail information from the backend server.
     *
     * Callback: function(item, status, request)
     */
  /*  get: function(id, callback){
        Vue.http.get(this.urlroot + this.id, callback);
    },

    getById: function(items, id){
        var result = null;
        var i = items.length;
        while (i--) {
            if (items[i].id == id)
            {
                result = items[i];
                break;
            }
        }
        return result;
    },

    indexof: function(items, id){
        var idx = null;
        var i = items.length;
        while (i--) {
            if (items[i].id == id)
            {
                idx = i;
                break;
            }
        }
        return i;
    },*/

    /* Update an item with its detail information to the backend server.
     *
     * Callback: function(item, status, request)
     */
   /* set: function(id, item, success_callback, error_callback){
        // alert("svc.set " + item);
        // Vue.http.put({id:id}, {item:this.item}, success_callback).error(error_callback);
        $.ajax({
            data:JSON.stringify(item),
            type: "PUT",
            contentType: "application/json",
            url: "/rest/change" + item.id,

        })
    },

    add: function(item, success_callback, error_callback){
        var self = this;
        var result = null;

        $.ajax({
            // context: this,
            data:JSON.stringify(item),
            type: "POST",
            contentType: "application/json",
            url: "/site/mvc/member/",
            // user: self.user;
            // password: self.password,
            // async: false,
            then: function(response, textStatus){
                // The REST service should return the object id.
                // this.items.push(result);
                item.id = response.id;
                if (success_callback != null)
                {
                    success_callback(response, textStatus);
                }
                result = response;
            },
            catch: function(XMLHttpRequest, textStatus, errorThrown){
                if (error_callback != null)
                {
                    error_callback(XMLHttpRequest, textStatus, errorThrown);
                }
                result = null;
            }
        });
        return result;
    },

    remove: function(item, success_callback, error_callback){
      var self = this;
      var result = null;
        //	Vue.http.delete({id:id}, success_callback).error(error_callback);
        $.ajax({
            // context: '', //item,
            type: "DELETE",
            contentType: "application/json",
            url: "http://localhost:8080/rest/delete" + item.id,
            then: function(response, textStatus){
                // The REST service should return the object id.
                // this.items.push(result);
                item.id = response.id;
                if (success_callback != null)
                {
                    success_callback(response, textStatus);
                }
                result = response;
            },

            catch: function(XMLHttpRequest, textStatus, errorThrown){
                //通常情况下textStatus和errorThrown只有其中�?个包含信�?
                //this;   //调用本次ajax请求时传递的options参数
                if (error_callback != null)
                {
                    error_callback(XMLHttpRequest, textStatus, errorThrown);
                }
                result = null;
            }
        })
    },

    remove2: function(item, success_callback, error_callback){
        Vue.http.delete({id:id}, success_callback).error(error_callback);
    }*/
};


var svc = Object.create(AppService);

// register modal component
/*Vue.component('itemeditor', {
  template: '#itemeditor-tpl',
  props:[{
    name: 'item',
    type: Object,
    twoWay: true,
    required: true
  },
    {
      name: 'mode',
      type: String,
      //default: 'modeList',
    },
    {
      name: 'onSubmit',
      type: Function,
      //required: true,
    },
    {
      name: 'onCancel',
      type: Function
      //type:String
    }
  ],
  data: function () {
    return {
      result: ''
    }
  },
  methods: {
    onSubmitClick: function(e){
      console.log("onSubmitClick: inside component itemeditor");
      this.result = this.onSubmit(this.mode, this.item);
    },
    onCancelClick: function(e){
      console.log("onCancelClick: inside component itemeditor");
      this.onCancel(this.mode, this.item);
    }
  },
  ready: function () {
    var self = this;
    // this.onLoad('message from child!')
  }
});*/
// register modal component
/*Vue.component('modal', {
    template: '#modal-template',
    props: {
        show: {
            type: Boolean,
            required: true,
            twoWay: true
        }
    }
});

Vue.component('datatable', {
    template: '#datatable-tpl',
    props:[{
        name: 'tabledef',
       type:Object,
       // type: String,
        twoWay: false,
        required: true
    },
        {
            name: 'onEdit',
            type: Function,
            //required: true,
        },
        {
            name: 'onRemove',
            type: Function,
        },
    ],

    methods: {
        onEditClick: function(item, e){
            console.log('editItem: ' + item.id.toString());
            //this.curitem = item;
            /!*
             var detail = null;
             svc.get({id: item.id}, function (detail, status, request) {
             this.$set('curitem', detail)
             });
             *!/
            //this.setMode('modeEdit');
        },

        onRemoveClick: function(item, e){
            console.log('removeItem' + item);
            //svc.remove(item);
            //this.items.$remove(item);
            //this.setMode('modeList');
        }
    }

});
Vue.component('itemadd', {
    template: '#itemadd-tpl',
    props:[{
        name: 'item',
        type: Object,
        twoWay: false,
        required: true
    },
        {
            name: 'mode',
            type: String,
           // default: 'modeList',
        },
        {
            name: 'onSubmit',
            type: Function,
            //required: true,
        },
        {
            name: 'onCancel',
            type: Function
        }
    ],
    data: function () {
        return {
            result: ''
        }
    },
    methods: {
        onSubmitClick: function(e){
            console.log("onSubmitClick: inside component itemeditor");
            this.result = this.onSubmit(this.mode, this.item);
        },
        onCancelClick: function(e){
            console.log("onCancelClick: inside component itemeditor");
            this.onCancel(this.mode, this.item);
        }
    },
    ready: function () {
        // this.onLoad('message from child!')
    }
});*/

var vm = new Vue({
    el: '#app',
    data: {
        currentView: 'itemeditor',
        begintime: '',
        endtime: '',
        firstname: '',
        midname: '',
        lastname: '',
        remotedevice: '',
        searchQuery: '',

        tabledef: {
            isShowHeader: true,
            isCheckable : true,
            columns : [
            ],
            operations: [
            ],
            items: [],
            onPagerChange : function (num){
                getData(num)
            },
            onSortChange : function (field, dir){
                console.log(field)
                console.log(dir)
            }
        },

        items: [
        ],
        curitem: {},

        selectall: true,
        mode: 'modeList', // modeList, modeItemView, modeAddNew, modeEdit
        modeTitle: "",



        showModal: false,
        parentMsg: "test",
        curdate: "2015.10.07",

        gridColumns: ['name', 'age'],
        gridData: [
        ]
    },

    components: {
    },

    methods: {
        __find: function(inputQuery, pagenum, pagesteps){
            var self = this;
            svc.find('', pagenum, pagesteps, this.items, function(data, status, request){
                // self.items.length = 0;
                self.$set('items', data)
                if (self.items.length > 0)
                {
                    self.$set("curitem", self.items[0]);
                }
            }, function(data, status, request){
                alert("Probably failed to connect the backend server! Pls check your server status!");
            });
        },
/*
        init: function(){
            svc.init();
            var datetime = new Date();
            datetime.getYear();        //获取当前年份(2�?)
            datetime.getFullYear();    //获取完整的年�?(4�?,1970-????)
            datetime.getMonth();       //获取当前月份(0-11,0代表1�?)
            datetime.getDate();        //获取当前�?(1-31)
            datetime.getDay();         //获取当前星期X(0-6,0代表星期�?)
            datetime.getTime();        //获取当前时间(�?1970.1.1�?始的毫秒�?)
            datetime.getHours();       //获取当前小时�?(0-23)
            datetime.getMinutes();     //获取当前分钟�?(0-59)
            datetime.getSeconds();     //获取当前秒数(0-59)
            datetime.getMilliseconds();    //获取当前毫秒�?(0-999)
            datetime.toLocaleDateString();     //获取当前日期
            this.curdate = datetime.toLocaleTimeString();     //获取当前时间
        },

        basicsearch: function(e){
            this.searchQuery = this.searchQuery.trim();
            if ((this.searchQuery).length == 0 )
            {
                document.getElementById("searchQuery").focus();
                alert("Please input search query");
            }
            this.__find(this.searchQuery, 1, 5);
        },

        advancedsearch: function(e){
            console.log("advanced search");
            console.log(e.target.tagName); // "BUTTON"
            console.log(e.targetVM === this); // true

            var inputs = new Array();
            inputs[0] = "{begintime:'";
            inputs[1] = this.begintime;
            inputs[2] = "', endtime:'";
            inputs[3] = this.endtime;
            inputs[4] = "', remotedevice:'";
            inputs[5] = this.remotedevice;
            inputs[6] = "', searchQuery:'";
            inputs[7] = this.searchQuery;
            inputs[8] = "'}";

            var inputQuery = inputs.join('');
            console.log("your input query condition is " + inputQuery);
            this.__find(inputQuery, 2, 5);
        },
        onSave: function(mode,item){
            var self = this;
            console.log("onSave");
            if (mode == 'modeAddNew')
            {
                svc.add(item, function(response, textStatus){
                    self.__find('', 1, 6);
                }, null);
            }
            else{
                svc.set(item.id, item, function(item, status, request){
                    var idx = svc.indexof(this.items, item.id);
                    if (idx != null)
                    {
                        vm.$set(this.items[idx], item);
                    }
                }, function(item, status, request){
                    alert("onSave failed to update!");
                });
            }
            setTimeout(function (){
                self.setMode('modeList');
            }, 20);
        },
        onCancel: function(mode,item){
            console.log("onCancel");
            this.setMode('modeList');
        },
        onEdit: function(item, e){
            console.log('editItem: ' + item.id.toString());
            this.curitem = item;
            /!*
             var detail = null;
             svc.get({id: item.id}, function (detail, status, request) {
             this.$set('curitem', detail)
             });
             *!/
            this.setMode('modeEdit');
        },
        onRemoveItem: function(item, e){
            console.log('removeItem' + item);
            svc.remove(item);
            this.items.$remove(item);
            this.setMode('modeList');
        },

        onRemoveSelected: function(e){
            console.log("removeSelected: " + e);
            var items = this.items;
            for (var i in items){
                if (items[i].selected)
                {
                    console.log(items[i] + ' is to be deleted!!!');
                    this.onRemoveItem(items[i], null);
                }
            }
        },
        setMode: function(newmode){
            if (this.mode != newmode)
            {
                this.mode = newmode;
                switch (newmode)
                {
                    case "modeList":
                        this.modeTitle = "";
                        break;
                    case "modeItemView":
                        this.modeTitle = " [详情]";
                        break;
                    case "modeEdit":
                        this.modeTitle = " [编辑]";
                        break;
                    case "modeAddNew":
                        this.modeTitle = " [新增]";
                        resetItem(this.curitem);
                        this.curitem.id=null;
                        break;
                    default:
                        this.modeTitle = "";
                }
            }
        },
        onChange:function(e){
          this.setMode('modeItemView');
      }*/
    },

  ready: function(){
   this.__find('', 1, 6);
   }
   });

setTimeout(function (){
    vm.init();
}, 20);

$(function () {
});




